package com.shanghaionstar.carmanage;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.mvp.base.core.PermissionCall;
import com.onstar.cn.mag.enumtype.CategoryType;
import com.onstar.cn.mag.publicService.response.ResponBannerEntity;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.ripple.view.RippleCustomBtn;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.nav.NavActivity;
import com.shanghaionstar.nav.NavMapFragment;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BannerUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.utils.NavHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import rx.Subscription;
import rx.functions.Action1;
import rx.subscriptions.Subscriptions;

/**
 * Created by Yonglang Hong on 2016/8/4.
 */
@ContentView(R.layout.onstar_home_ovd_rate)
public class CheckMaintainActivity extends SwipeActivity {
    @FindViewById
    private LinearLayout oil_life_layout, ove_tire_layout, fuel_tank_layout,
            maintain_layout, maintain_info_layout, battery_level_layout;

    @FindViewById
    private TextView oil_life, oil_life_hint, oil_life_hint2, ove_tire, ove_tire_hint, fuel_tank_info,
            fuel_tank_info_hint, maintain_info, maintain_info_1, battery_level_info;

    @FindViewById
    private ImageView img_ad, img_noAdvice;

    @FindViewById(background = R.drawable.button_corner)
    private RippleCustomBtn btn_around_dealer;

    @FindViewById
    private View ll_advice;

    private List<String> tireList = new ArrayList<>();

    public static final String FROM = "from";

    Bundle bundle;

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        setUpViews();
    }

    private void setUpViews() {
//        setUpAdImg(null);

        //判断如果不是车主隐藏“联系经销商按钮”
        String loginRole = ApplicationUtil.getInstance().getLoginRole();
        if (!loginRole.equalsIgnoreCase(JoinMeConstants.OWNER)) {
            btn_around_dealer.setVisibility(View.GONE);
        }

        loadBanner();
        showIfEmptyStatus();
    }

    /**
     * 根据是否有车况数据显示建议UI
     */
    private void showIfEmptyStatus() {
        bundle = getIntent().getExtras();
        if (bundle == null || bundle.isEmpty()) {
            ll_advice.setVisibility(View.GONE);
            img_noAdvice.setVisibility(View.VISIBLE);
            return;
        }
        img_noAdvice.setVisibility(View.GONE);
        ll_advice.setVisibility(View.VISIBLE);
        setUpPsi();
        setUpOil();
        setUpOdoMeter();
        setUpBattery();
        setUpFuelTankInfo();
    }

    protected Subscription subscription = Subscriptions.empty();

    private void loadBanner() {
        BannerUtil util = new BannerUtil(this);
        subscription = util.commandDataList(CategoryType.MAINTAIN_BANNER.value()).subscribeOn(getScheduler().backgroundThread()).observeOn(getScheduler().mainThread())
                .subscribe(new Action1<List<ResponBannerEntity>>() {
                    @Override
                    public void call(List<ResponBannerEntity> response) {
                        if (response != null && response.size() > 0) {
                            setUpAdImg(response);
                        } else {
                            img_ad.setVisibility(View.GONE);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        img_ad.setVisibility(View.GONE);
                    }
                });
    }

    private void setUpAdImg(List<ResponBannerEntity> bannerEntities) {
//        final List<ResponBannerEntity> bannerEntities = OnstarApplication.getApplication().getBannerEntities();
        if (bannerEntities != null && !bannerEntities.isEmpty()) {
            final DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.home_banner_failed)
                    .showImageForEmptyUri(R.drawable.home_banner_failed).showImageOnFail(R.drawable.home_banner_failed)
                    .resetViewBeforeLoading(true).cacheInMemory(true).cacheOnDisc(false).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                    .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(100)).build();
            final ResponBannerEntity entity = bannerEntities.get(0);
            img_ad.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(entity.getImgUrl(), img_ad, options);
            img_ad.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (entity != null) {
                        BannerUtil util = new BannerUtil(CheckMaintainActivity.this);
                        util.bannerClick(entity, CheckMaintainActivity.this, FunctionNameFindId.UnSend, getScheduler(), null);
                    } else {
                        img_ad.setVisibility(View.GONE);
                    }
                }
            });
        }
    }
//            img_ad.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (entity != null) {
//                        BannerUtil util =  new BannerUtil(CheckMaintainActivity.this);
//                        util.bannerClick(entity,CheckMaintainActivity.this, FunctionNameFindId.UnSend,getScheduler(),null);
////                        Intent intent = new Intent();
////                        String url = TextUtils.isEmpty(entity.getContentUrl())
////                                ? entity.getUrl() : entity.getContentUrl();
////                        if (!CommonUtil.isNull(entity.getShowType())) {
////                            String showType = entity.getShowType();
////                            if ("1".equals(showType)) {
////                                LogManager.getInstance().d("showType:" + showType);
////                                intent.setClass(CheckMaintainActivity.this, BannerActivity.class);
////                                intent.putExtra("content", entity.getContent());
////                                /**********如果content为空则根据URI显示:该逻辑在BannerActivity Line:100判断*******/
////                                intent.putExtra("uri", url);
////                                intent.putExtra("showType", entity.getShowType());
////                                String isScaling = entity.getIsScaling();
////                                intent.putExtra("isScaling", isScaling == null ? "" : isScaling);
////                            } else if ("3".equals(showType) || "2".equals(showType)) {
////                                LogManager.getInstance().d("showType:" + showType);
////                                intent.setClass(CheckMaintainActivity.this, BannerActivity.class);
////                                intent.putExtra("uri", url);
////                                intent.putExtra("showType", entity.getShowType());
////                                String isScaling = entity.getIsScaling();
////                                intent.putExtra("isScaling", isScaling == null ? "" : isScaling);
////                            } else if ("4".equals(showType)) {
////                                LogManager.getInstance().d("showType:" + showType);
////                                intent.setAction("android.intent.action.VIEW");
////                                Uri content_url = Uri.parse(url);
////                                intent.setData(content_url);
////                            }
////                        } else {
////                            intent.setClass(CheckMaintainActivity.this, BannerActivity.class);
////                            intent.putExtra("uri", url);
////                        }
////                        intent.putExtra("receiveType", BannerLayout.BANNER_TAG);
////                        intent.putExtra("title", entity.getTitle());
////                        intent.putExtra("isH5Title", entity.getIsH5Title());
////                        if (bundle != null && !bundle.containsKey(FROM))
////                            BusinessUtil.sendReportByClickType(CheckMaintainActivity.this, FunctionNameFindId.Maintainence_banner1.getStringValue());
////                        startActivity(intent);
////                    }
//                }
//            })
//        } else {
//            img_ad.setVisibility(View.GONE);
//        }
//    }

    /**
     * 显示胎压
     */
    private void setUpPsi() {
        String leftFront = bundle.getString(Constants.TIRE_PRESSURE_LF); // 左前
        String leftRear = bundle.getString(Constants.TIRE_PRESSURE_LR);  // 左后
        String rightFront = bundle.getString(Constants.TIRE_PRESSURE_RF);// 右前
        String rightRear = bundle.getString(Constants.TIRE_PRESSURE_RR); // 右后

        if (!CommonUtil.isNull(leftFront)
                && !CommonUtil.isNull(leftRear)
                && !CommonUtil.isNull(rightFront)
                && !CommonUtil.isNull(rightRear)) {
            tireList.add(leftFront.toLowerCase(Locale.CHINA));
            tireList.add(leftRear.toLowerCase(Locale.CHINA));
            tireList.add(rightFront.toLowerCase(Locale.CHINA));
            tireList.add(rightRear.toLowerCase(Locale.CHINA));
            if (ove_tire_layout != null) {
                ove_tire_layout.setVisibility(View.VISIBLE);
            }
            if (!tireList.contains("yellow") && !tireList.contains("red")) {
                ove_tire.setText(R.string.tire_info_full);
                ove_tire_hint.setText(R.string.tire_info_full_hint);
                ove_tire.setTextColor(getResources().getColor(R.color.home_green));
            } else if (tireList.contains("red")) {
                ove_tire.setText(R.string.tire_info_risk);
                ove_tire_hint.setText(R.string.tire_info_risk_hint);
                ove_tire.setTextColor(getResources().getColor(R.color.home_red));
            } else {
                ove_tire.setText(R.string.tire_info_low);
                ove_tire_hint.setText(R.string.tire_info_low_hint);
                ove_tire.setTextColor(getResources().getColor(R.color.home_yellow));
            }
        } else {
            ove_tire_layout.setVisibility(View.GONE);
        }
    }

    /**
     * 显示机油余量
     */
    private void setUpOil() {
        int oilLife = bundle.getInt(Constants.OIL_LIFE, -1);
        if (oilLife < 0) {
            oil_life_layout.setVisibility(View.GONE);
        } else {
            oil_life_layout.setVisibility(View.VISIBLE);
            if (oilLife > 20 && oilLife <= 100) {
                oil_life.setText(R.string.oil_life_full);
                oil_life_hint.setText(R.string.oil_life_full_hint);
                oil_life_hint2.setVisibility(View.GONE);
                oil_life.setTextColor(getResources().getColor(R.color.home_green));
            } else if (oilLife > 0 && oilLife <= 20) {
                oil_life.setText(R.string.oil_life_low);
                oil_life_hint.setText(R.string.oil_life_low_hint);
                oil_life_hint2.setText(R.string.oil_life_low_hint_2);
                oil_life_hint2.setVisibility(View.VISIBLE);
                oil_life.setTextColor(getResources().getColor(R.color.home_yellow));
            } else {
                oil_life.setText(R.string.oil_life_risk);
                oil_life_hint.setText(R.string.oil_life_risk_hint);
                oil_life_hint2.setText(R.string.oil_life_risk_hint_2);
                oil_life_hint2.setVisibility(View.VISIBLE);
                oil_life.setTextColor(getResources().getColor(R.color.home_red));
            }
        }
    }

    /**
     * 显示总里程
     */
    private void setUpOdoMeter() {
        int odometer = getIntent().getIntExtra(Constants.ODOMETER, -1);// 总行驶里程
        if (odometer < 0 || odometer < 9000) {
            maintain_layout.setVisibility(View.GONE);
        } else {
            maintain_layout.setVisibility(View.VISIBLE);
            List<Integer> strList = new ArrayList<Integer>();
            if (odometer % 10000 >= 9500 || odometer % 10000 <= 500) {
                strList.add(R.string.air_filter);
                strList.add(R.string.fuel_filter);
                strList.add(R.string.power_fuel);
                strList.add(R.string.air_damper);
            }
            if (odometer % 20000 >= 19000 || odometer % 20000 <= 1000) {
                strList.add(R.string.nozzle_fuel_line);
            }
            if (odometer % 25000 >= 22500 || odometer % 25000 <= 2500) {
                strList.add(R.string.braking_fluid);
            }
            if (odometer % 40000 >= 36000 || odometer % 40000 <= 4000) {
                strList.add(R.string.transmission_fluid);
                strList.add(R.string.engine_coolant);
            }
            if (strList.size() > 0) {
                for (int i = 0; i < strList.size() / 2; i++) {
                    View view = LayoutInflater.from(CheckMaintainActivity.this).inflate(
                            R.layout.onstar_home_ovd_rate_item, null);
                    maintain_info = (TextView) view.findViewById(R.id.maintain_info);
                    maintain_info_1 = (TextView) view.findViewById(R.id.maintain_info_1);
                    maintain_info.setText(strList.get(i));
                    if (strList.size() % 2 != 0) {
                        maintain_info_1.setText(strList.get(i + strList.size() / 2 + 1));
                    } else {
                        maintain_info_1.setText(strList.get(i + strList.size() / 2));
                    }
                    maintain_info_layout.addView(view);
                }
                if (strList.size() % 2 != 0) {
                    View view = LayoutInflater.from(CheckMaintainActivity.this).inflate(
                            R.layout.onstar_home_ovd_rate_item, null);
                    maintain_info = (TextView) view.findViewById(R.id.maintain_info);
                    maintain_info_1 = (TextView) view.findViewById(R.id.maintain_info_1);
                    maintain_info.setText(strList.get(strList.size() / 2 + strList.size() % 2 - 1));
                    maintain_info_layout.addView(view);
                }
            } else {
                maintain_layout.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 显示燃油余量
     */
    private void setUpFuelTankInfo() {
        int fuelTankInfo = getIntent().getIntExtra(Constants.FUEL_TANK_INFO, -1);
        if (fuelTankInfo < 0) {
            fuel_tank_layout.setVisibility(View.GONE);
        } else {
            fuel_tank_layout.setVisibility(View.VISIBLE);
            if (fuelTankInfo > 92 && fuelTankInfo <= 100) {
                fuel_tank_info.setText(R.string.fuel_tank_info_full);
                fuel_tank_info_hint.setText(R.string.fuel_tank_info_full_hint);
                fuel_tank_info.setTextColor(getResources().getColor(R.color.home_green));
            } else if (fuelTankInfo > 30 && fuelTankInfo <= 92) {
                fuel_tank_info.setText(R.string.fuel_tank_info_full);
                fuel_tank_info_hint.setText(R.string.fuel_tank_info_full_hint_2);
                fuel_tank_info.setTextColor(getResources().getColor(R.color.home_green));
            } else if (fuelTankInfo > 8 && fuelTankInfo <= 30) {
                fuel_tank_info.setTextColor(getResources().getColor(R.color.home_yellow));
                fuel_tank_info.setText(R.string.fuel_tank_info_low);
                fuel_tank_info_hint.setText(R.string.fuel_tank_info_low_hint);
            } else {
                fuel_tank_info.setText(R.string.fuel_tank_info_risk);
                fuel_tank_info_hint.setText(R.string.fuel_tank_info_risk_hint);
                fuel_tank_info.setTextColor(getResources().getColor(R.color.home_red));
            }
        }
    }

    /**
     * 显示充电信息
     */
    private void setUpBattery() {
        String batteryLevel = getIntent().getStringExtra(Constants.EV_BATTERY_LEVEL);//电动车充电百分比
        if (!CommonUtil.isNull(batteryLevel)) {
            float iBatteryLevel = Float.valueOf(batteryLevel);
            if (iBatteryLevel > 20 && iBatteryLevel <= 100) {
                battery_level_info.setText(R.string.battery_info_full);
                battery_level_info.setTextColor(getResources().getColor(R.color.home_green));
            } else if (iBatteryLevel > 0 && iBatteryLevel <= 20) {
                battery_level_info.setText(R.string.battery_info_low);
                battery_level_info.setTextColor(getResources().getColor(R.color.home_yellow));
            } else {
                battery_level_info.setText(R.string.battery_info_low);
                battery_level_info.setTextColor(getResources().getColor(R.color.home_red));
            }
        } else {
            battery_level_layout.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.btn_around_dealer)//联系周边经销商
    public void onClick(View v) {
//        BusinessUtil.sendReportByClickType(this,
//                FunctionNameFindId.Maintenance_contactdealer.getStringValue());
        if (NavHolder.getInstance(this).getMyLocation() == null) {
            requestRunTimePermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionCall() {
                @Override
                public void requestSuccess() {
                    NavHolder.getInstance(CheckMaintainActivity.this).findMyLocation();
                }

                @Override
                public void refused() {

                }
            });

        } else {
            if (bundle != null && bundle.containsKey(FROM))
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.MaintenanceSgst_ContactDealer.getStringValue());
            else
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Maintainence_Dealerreserve.getStringValue());
            Intent intent = new Intent(this, NavActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(FinalConstants.JUMP_FLAG, NavMapFragment.class.getSimpleName());
            bundle.putString(FinalConstants.FROM_PAGE, NavMapFragment.class.getSimpleName());
            PoiItemInfo poiItemInfo = new PoiItemInfo();
            poiItemInfo.setLatitude(NavHolder.getInstance(this).getMyLocation().getLatitude());
            poiItemInfo.setLongitude(NavHolder.getInstance(this).getMyLocation().getLongitude());
            bundle.putSerializable("poiItemInfo", poiItemInfo);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (bundle != null && bundle.containsKey(FROM))
            BusinessUtil.sendReportByClickType(this, FunctionNameFindId.MaintenanceSgst_Return.getStringValue());
        else
            BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Maintainence_back.getStringValue());
    }
}
